package com.zhuhjay.boot.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.boot.mapper.MemberMapper;
import com.zhuhjay.domain.entity.Member;
import com.zhuhjay.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(Map<String, Object> map) {
        String telephone = (String) map.get("telephone");
        // 判断用户是否是会员
        Member member = baseMapper.selectOne(new QueryWrapper<Member>()
                .eq("phoneNumber", telephone));
        if( member == null ){
            // 不是会员自动注册
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            baseMapper.insert(member);
        }

        // 将会员信息保存到Redis中 30 分钟
        String memberJson = JSON.toJSON(member).toString();
        redisTemplate.opsForValue().set(telephone, memberJson, 30, TimeUnit.MINUTES);
    }

    @Override
    public Map<String, Object> getReport() {
        Map<String, Object> map = new HashMap<>();
        // 构造最近几个月的日期时间
        Calendar calendar = Calendar.getInstance();
        //获得当前日期之前12个月的日期
        calendar.add(Calendar.MONTH,-12);

        List<String> months = new ArrayList<>();
        for( int i = 0; i < 12; i++ ){
            // 日期往后推一个月
            calendar.add(Calendar.MONTH,1);
            months.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
        }

        map.put("months",months);

        List<Integer> memberCount = new ArrayList<>();
        months.forEach(month -> {
            month += "-31";
            // 查询在这之前用户的数量
            Integer count = baseMapper.selectCount(new QueryWrapper<Member>()
                    .lt("regTime", month));
            memberCount.add(count);
        });

        map.put("memberCount", memberCount);

        return map;
    }
}
